package com.exartisan.yn_event;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.exartisan.adapter.FeedAdapter;
import com.exartisan.bean.Event;
import com.exartisan.bean.FbComment;
import com.exartisan.network.FacebookResponseParser;
import com.exartisan.network.FbConnnector;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.ParametersBuilder;
import com.exartisan.network.RestConnector;
import com.exartisan.util.DialogCommentUtil;
import com.exartisan.util.FbUtil;
import com.exartisan.util.OnCommentDialogClickListener;
import com.exartisan.ynevent.BaseActivity;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.image.SmartImageView;

public class Event_Feeds extends BaseActivity{
	private ListView feedList;
	private Event event;
	private ArrayList<FbComment> comments;
	private FeedAdapter feedAdapter;
	private TextView tvDes;
	private SmartImageView imgEvent;
	private WebView wvComment;
	private ProgressBar prBar;
	private ImageButton btnReloadComment;
	private String urlComment;
	private ImageButton btnComment;
	private ImageButton btnShare;
	private ImageButton btnLike;
	private boolean liked = false;

	
//	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
//		com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
//	      inflater.inflate(R.menu.action_bar, menu);
//		return true;
//	}
	
	@Override
	protected void setUpActionBar() {
		super.setUpActionBar();
		ActionBar bar = getSupportActionBar();
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		bar.setDisplayShowCustomEnabled(true);
		bar.setCustomView(R.layout.ab_feedscreen);
	}

	@Override
	protected void initUI() {
		setContentView(R.layout.activity_feeds);
		
		//tvDes = (TextView) findViewById(R.id.tv_event_desc);
		//imgEvent = (SmartImageView) findViewById(R.id.img_event);
		//wvComment = (WebView) findViewById(R.id.wvFeed);
		//prBar = (ProgressBar) findViewById(R.id.progressBar);
		btnReloadComment = (ImageButton) findViewById(R.id.mnRefresh);
		btnComment = (ImageButton) findViewById(R.id.mnComment);
		btnShare = (ImageButton) findViewById(R.id.mnShare);
		prBar = (ProgressBar) findViewById(R.id.progressBar);
		//btnLike = (ImageButton) findViewById(R.id.btn_like);
		
		feedList = (ListView) findViewById(R.id.feeds_list);
	}

	@Override
	protected void initProcess() {
		
		btnComment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DialogCommentUtil.showDialogComment(getActivity(), new OnCommentDialogClickListener() {
					
					@Override
					public void onClick(View v) {
						
					}
					
					@Override
					public void onClick(View v, String msg) {
						final String message = msg;
						Session session = Session.getActiveSession();
						if(session==null||session.isClosed()) Session.openActiveSession(getActivity(), true, new StatusCallback() {
							
							@Override
							public void call(Session session, SessionState state, Exception exception) {
								if(session != null) 
									if (state.isOpened()){
										comment(message);
								}
							}
						}); else
							comment(message);
					}
				});
			}
		});
		
		btnReloadComment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getFbComments();
			}
		});
		
		btnShare.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Session session = Session.getActiveSession();
				if(session==null||session.isClosed()) Session.openActiveSession(getActivity(), true, new StatusCallback() {
					
					@Override
					public void call(Session session, SessionState state, Exception exception) {
						if(session != null){
							if(state.isOpened()){
								FbUtil.ShareToFb(getActivity(), event.getEventName(), event.getDescription(), FbUtil.YN_LINK, event.getThumbUrl());
							}
						}
					}
				}); else
					FbUtil.ShareToFb(getActivity(), event.getEventName(), event.getDescription(), FbUtil.YN_LINK, event.getThumbUrl());
			}
		});
		
		//tvDes.setTypeface(FontUtil.loadFontFromAssets(this, FontUtil.TAHOMABD));
		
		comments = new ArrayList<FbComment>();
		event = getIntent().getParcelableExtra("event");
		//event = new Event();
		
		//tvDes.setText(event.getEventName());
		//imgEvent.setImageUrl(event.getThumbUrl());
		/*imgEvent.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getBaseContext(), DetailActivity.class);
				i.putExtra("event", event);
				startActivity(i);
			}
		});
		
		btnReloadComment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				wvComment.loadUrl(urlComment);
				
			}
		});*/
		
		//event = new Event();
		feedAdapter = new FeedAdapter(this, event, comments);
		/*wvComment.getSettings().setJavaScriptEnabled(true);
		wvComment.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return false;
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				prBar.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
			
			
		});*/
		//wvComment.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		//getCommentWebForm();
		feedList.setAdapter(feedAdapter);
		getFbComments();
		checkEventLike();
		
		feedList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				if (pos==0) {
					Intent i = new Intent(getBaseContext(), DetailActivity.class);
					i.putExtra("event", event);
					startActivity(i);
				}
			}
		});
		
	}
	
	public void goToDetail(View v){
		Intent i = new Intent(this, DetailActivity.class);
		startActivity(i);
	}
	
	private void getFbComments(){
		if(NetworkUtility.checkNetworkState(getApplicationContext())){
			prBar.setVisibility(View.VISIBLE);
			//Log.d("feedID", event.getFbFeedID());
			RequestParams params = new RequestParams("ids", event.getFbFeedID());
			FbConnnector.get(null, "/comments", params, new AsyncHttpResponseHandler(){
				
				@Override
				public void onSuccess(int arg0, String response) {
					prBar.setVisibility(View.GONE);
					if (response == null){
						Toast.makeText(getApplicationContext(), "Không thể tải bình luận", Toast.LENGTH_SHORT).show();
						return;
					}
					Log.d("fbRes", response.toString());
					comments = FacebookResponseParser.getComments(response, event.getFbFeedID());
					Log.d("comments_num", comments.size() + "");
					feedAdapter.setFbComments(comments);
					feedAdapter.notifyDataSetChanged();
					super.onSuccess(arg0, response);
				}
				
				@Override
				public void onFailure(Throwable arg0, String arg1) {
					prBar.setVisibility(View.GONE);
					Toast.makeText(getApplicationContext(), "Không thể tải bình luận", Toast.LENGTH_SHORT).show();
					super.onFailure(arg0, arg1);
				}
				
			});
		} else Toast.makeText(this, "Không có kết nối", Toast.LENGTH_SHORT).show();
	}
	
	private void comment(final String comment){
		Log.d("token", Session.getActiveSession().getAccessToken());
		
		FbConnnector.post(event.getFbFeedID(), "/comments?access_token=" + FbUtil.ACCESS_TOKEN, new RequestParams("message", comment), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int arg0, String response) {
				Log.d("commentResponse", response.toString());
				getFbComments();
				super.onSuccess(arg0, response);
			}
			
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				Toast.makeText(getActivity(), "Không thể đăng bình luận", Toast.LENGTH_SHORT).show();
				Log.d("commentResponse", "fail");
				super.onFailure(arg0, arg1);
			}
		});
		//session.requestNewPublishPermissions(new NewPermissionsRequest(getActivity(), Arrays.asList("publish_stream", "read_stream")));
		/*FbConnnector.post(event.getFbFeedID(), "/comments?access_token=CAACTcgcPDfIBAGqOf530DGu2o9q0LNYNHxy8WZBG6Datw9JBv25vxKXzKLxdRDrVXGxJwxKcR1Cgs6ZBZCAsBcYPSfKCeA8QpMD7cZAt5PHszzMhJ8fVwzbiJ75ZB4xekCTvoFQdkGeVlOmkWzSWHIEEZBilSCvXrWrfI7ola25wnJjn5wzmnIaTXNtYTgBJm9CBTnWYOLirs8gB9Sd1fCQhvQYnnpOgDgxmozTQAOHQZDZD", new RequestParams("message", comment), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int arg0, String response) {
				Log.d("commentResponse", response.toString());
				getFbComments();
				super.onSuccess(arg0, response);
			}
			
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				Toast.makeText(getActivity(), "Không thể đăng bình luận", Toast.LENGTH_SHORT).show();
				Log.d("commentResponse", "fail");
				super.onFailure(arg0, arg1);
			}
		});*/
	}
	
	private void getCommentWebForm(){
		if(NetworkUtility.checkNetworkState(getApplicationContext())){
			RestConnector.getWithUrl(NetworkUtility.COMMENTAPI, ParametersBuilder.BuildGetCommentWebFormParams("1", "1"), new AsyncHttpResponseHandler(){
				
				@Override
				public void onSuccess(int arg0, String response) {
					if (response == null){
						Toast.makeText(getApplicationContext(), "Không thể tải bình luận", Toast.LENGTH_SHORT).show();
						return;
					}
					Log.d("fbRes", response.toString());
					//comments = FacebookResponseParser.getComments(response, "http://www.haivl.com/photo/1095177");
					//Log.d("comments_num", comments.size() + "");
					//feedAdapter.setFbComments(comments);
					//feedAdapter.notifyDataSetChanged();
					urlComment = response;
					wvComment.loadUrl(response);
					super.onSuccess(arg0, response);
				}
				
				@Override
				public void onFailure(Throwable arg0, String arg1) {
					Toast.makeText(getApplicationContext(), "Không thể tải bình luận", Toast.LENGTH_SHORT).show();
					super.onFailure(arg0, arg1);
				}
				
			});
		} else Toast.makeText(this, "Không thể tải bình luận", Toast.LENGTH_SHORT).show();
	}
	
	private SherlockFragmentActivity getActivity(){
		return this;
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	   Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

	}
	
	public void onLikeClicked(View v){
		
		if(NetworkUtility.checkNetworkState(getApplicationContext())){
			
			if(!liked) {
				FbConnnector.post(event.getFbFeedID(), "/likes?access_token=" + FbUtil.ACCESS_TOKEN, null, new AsyncHttpResponseHandler(){
				@Override
				public void onSuccess(int arg0, String response) {
					//btnLike.setBackgroundResource(R.drawable.btn_liked);
					liked = true;
					feedAdapter.setLiked(true);
					feedAdapter.notifyDataSetChanged();
					Log.d("commentResponse", response.toString());
					Toast.makeText(getActivity(), "Bạn đã like bài viết", Toast.LENGTH_SHORT).show();
					super.onSuccess(arg0, response);
				}
				
				@Override
				public void onFailure(Throwable arg0, String arg1) {
					//btnLike.setBackgroundResource(R.drawable.btn_liked);
					Toast.makeText(getActivity(), "Lỗi kết nối", Toast.LENGTH_SHORT).show();
					Log.d("commentResponse", "fail");
					super.onFailure(arg0, arg1);
				}
			});
				} else {
					FbConnnector.delete(event.getFbFeedID(), "/likes?access_token=" + FbUtil.ACCESS_TOKEN, new AsyncHttpResponseHandler(){
						@Override
						public void onSuccess(int arg0, String response) {
							//btnLike.setBackgroundResource(R.drawable.btn_like);
							liked = false;
							feedAdapter.setLiked(false);
							feedAdapter.notifyDataSetChanged();
							Log.d("commentResponse", response.toString());
							Toast.makeText(getActivity(), "Bạn đã hủy like bài viết", Toast.LENGTH_SHORT).show();
							super.onSuccess(arg0, response);
						}
						
						@Override
						public void onFailure(Throwable arg0, String arg1) {
							//btnLike.setBackgroundResource(R.drawable.btn_like);
							Toast.makeText(getActivity(), "Lỗi kết nối", Toast.LENGTH_SHORT).show();
							Log.d("commentResponse", "fail");
							super.onFailure(arg0, arg1);
						}
					});
				}
			
			
		} else Toast.makeText(this, "Không có kết nối", Toast.LENGTH_SHORT).show();
		
	}
	
	public void onCommentclicked(View v){
		DialogCommentUtil.showDialogComment(getActivity(), new OnCommentDialogClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
			
			@Override
			public void onClick(View v, String msg) {
				final String message = msg;
				Session session = Session.getActiveSession();
				if(session==null||session.isClosed()) Session.openActiveSession(getActivity(), true, new StatusCallback() {
					
					@Override
					public void call(Session session, SessionState state, Exception exception) {
						if(session != null) 
							if (state.isOpened()){
								comment(message);
						}
					}
				}); else
					comment(message);
			}
		});
	}
	
	public void onImageClicked(View v){
		Intent i = new Intent(getBaseContext(), DetailActivity.class);
		i.putExtra("event", event);
		startActivity(i);
	}
	
	private void checkEventLike(){
		if (NetworkUtility.checkNetworkState(getActivity())){
			FbConnnector.get(event.getFbFeedID(), "/likes?access_token=" + FbUtil.ACCESS_TOKEN, null, new AsyncHttpResponseHandler(){
				@Override
				public void onSuccess(int arg0, String response) {
					Log.d("commentResponse", response.toString());
					try {
						JSONObject res = new JSONObject(response);
						JSONArray data = res.getJSONArray("data");
						for (int i=0; i<data.length(); i++){
							String id = data.getJSONObject(i).getString("id");
							if (id.equals("100001832988926")) {
								Log.d("liked", "ok");
								liked = true;
								feedAdapter.setLiked(true);
								feedAdapter.notifyDataSetChanged();
							}
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					super.onSuccess(arg0, response);
				}
				
				@Override
				public void onFailure(Throwable arg0, String arg1) {
					Log.d("commentResponse", "fail");
					super.onFailure(arg0, arg1);
				}
			});
		}
	}

}
